/**
 * http配置
 */

import axios from 'axios'
import router from '../router/routes'
import store from '../vuex/store'
import messages from '../i18n/langs/index'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  //baseURL: "http://"+window.location.hostname+":8085", // api的base_url
  timeout: 15000 // 请求超时时间
})

// http request 拦截器
service.interceptors.request.use(
    config => {
      window.f7.preloader.show();
    	if(!config[0]){//不需要传递token
    		if (localStorage.user) {
              config.headers.token = JSON.parse(localStorage.user).token;
	       }
    	}
        return config;
    },
    err => {
        return Promise.reject(err);
    });

// http response 拦截器
service.interceptors.response.use(
    response => {
        const res = response.data
          if (res.code !== 0) {

              if (res.code === 2) {
                let msg = messages[store.state.global.lang].ApiMessage[res.data[0].defaultMessage];
                 window.f7.toast.create({
                    text: msg?msg:res.data[0].defaultMessage,
                    closeTimeout: 2000,
                  }).open();
               }else if (res.code === 401) {
                 console.log('token无效');
                 localStorage.removeItem('user');
                 store.dispatch('initGlobalPropertys',[{key:'isLogin',value:false}])

              }else{
                let msg = messages[store.state.global.lang].ApiMessage[res.msg];
                window.f7.toast.create({
                   text: msg?msg:res.msg,
                   closeTimeout: 2000,
                 }).open();
              }


               window.f7.preloader.hide();
                return Promise.reject('error')
          }else{
             window.f7.preloader.hide();
              return response.data;
          }

    },
    error => {
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    // 401 清除token信息并跳转到登录页面
                      localStorage.removeItem('user');
                      alert(401);
            }
        }
        // console.log(JSON.stringify(error));//console : Error: Request failed with status code 402
        return Promise.reject(error)
    });

export default service;
